<template>
  <div
    class="container"
    v-infinite-scroll="loadNewTimePosts"
    infinite-scroll-distance="1"
    infinite-scroll-disabled="disabled"
    style="height: 100vh"
  >
    <div class="b">
      <div class="left_box">
        <div class="search_input">
          <!-- <el-cascader
            v-model="typeId"
            :options="options"
            @change="handleChange"
            style="width: 30%"
            filterable
            placeholder="请选择分类"
            clearable
          ></el-cascader> -->
          <el-select
            v-model="sort"
            placeholder="请选择查询类型"
            style="width: 20%"
            @change="searchQuery"
          >
            <el-option
              v-for="item in [
                { label: '最新发布', value: 1 },
                { label: '最多点赞', value: 2 },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model="keyword"
            placeholder="请输入关键词"
            style="width: 60%; margin-left: 10px"
          ></el-input>
          <el-button
            round
            icon="el-icon-search"
            @click="searchQuery"
            style="width: 20%; margin-left: 10px"
            :loading="loading"
            >查询帖子</el-button
          >
        </div>
        <div class="search_class">
          <div class="search_class_type">
            <div
              :class="{ class_avtive: isPrivate === false }"
              @click="set_search_class_type(false)"
            >
              公开
            </div>
            <div
              :class="{ class_avtive: isPrivate === true }"
              @click="set_search_class_type(true)"
            >
              仅社团
            </div>
          </div>
          <div class="one_class">
            <div
              :class="{ class_avtive_1: one_class === '' }"
              @click="set_one_class('')"
            >
              全部
            </div>
            <div
              v-for="(v, i) in options"
              :key="i"
              :class="{ class_avtive_1: one_class === v.value }"
              @click="set_one_class(v.value)"
            >
              {{ v.label }}
            </div>
          </div>
          <div class="two_class">
            <div
              :class="{ class_avtive_1: two_class === '' }"
              @click="set_two_class('')"
            >
              不限
            </div>
            <div
              v-for="(v, i) in getTwoClass()"
              :key="i"
              :class="{ class_avtive_1: two_class === v.value }"
              @click="set_two_class(v.value)"
            >
              {{ v.label }}
            </div>
          </div>
        </div>
        <div>
          <div class="topic_box" v-for="item in posts" :key="item.id">
            <div class="top">
              <img :src="item.userAvatar" class="headPortrait" />
              <div class="userContent">
                <div
                  style="
                    display: flex;
                    align-items: flex-end;
                    flex-direction: row;
                  "
                >
                  <div class="header-name">
                    {{ item.userName }}
                  </div>
                  <div v-show="item.isJoin">
                    <el-tag
                      effect="dark"
                      style="margin-left: 5px; height: 20px; line-height: 18px"
                    >
                      成员
                    </el-tag>
                  </div>
                  <el-tag
                    v-for="(items, index) in item.userUseTitle.filter(
                      (item) => !item.isPrivate
                    )"
                    :key="index"
                    type="success"
                    effect="dark"
                    style="margin-left: 5px; height: 20px; line-height: 18px"
                  >
                    {{ items.title }}
                  </el-tag>
                </div>

                <div class="header-fot">
                  <p>{{ item.gmtCreate }}</p>
                </div>
              </div>
            </div>
            <div></div>
            <div
              class="middle"
              v-html="item.content"
              @click="$router.push(`/ywbd/postDetails?id=${item.id}`)"
            ></div>

            <div class="imgs" v-if="item.postImage">
              <el-image
                style="width: 100%; height: auto"
                :src="item.postImage"
                :preview-src-list="[item.postImage]"
              >
              </el-image>
            </div>

            <div class="bottom">
              <div class="handle_box">
                <span class="dz" @click="toggleLike(item.id, item.likes)">
                  <svg-icon
                    icon-class="giveTheThumbs-up"
                    v-show="!item.isGiveTheThumbs_up"
                  />
                  <svg-icon
                    icon-class="redGiveTheThumbs-up"
                    v-show="item.isGiveTheThumbs_up"
                  />
                  <span>{{ item.likes }}</span>
                </span>
                <span
                  class="sc marginsLeft"
                  @click="toggleCollect(item.id, item.collects)"
                >
                  <svg-icon icon-class="collection" v-show="!item.isCollects" />
                  <svg-icon
                    icon-class="collectionAfter"
                    v-show="item.isCollects"
                  />
                  <span>{{ item.collects }}</span>
                </span>
                <span
                  class="pl marginsLeft"
                  @click="$router.push(`/ywbd/postDetails?id=${item.id}`)"
                >
                  <svg-icon icon-class="information" />
                  <span>{{ item.comments }}</span>
                </span>
                <span class="watchs marginsLeft">
                  <svg-icon icon-class="watchs" />
                  <span>{{ item.views }}</span>
                </span>
              </div>
            </div>
          </div>
        </div>
        <p style="text-align: center" v-if="loading">加载中...</p>
        <p style="text-align: center" v-if="posts && posts[0] && noMorePosts">
          没有更多了
        </p>
        <el-empty description="暂无数据" v-if="!posts || !posts[0]"></el-empty>
      </div>
      <div class="right_box">
        <div class="card" id="fbht" @click="$router.push('/ywbd/pushComment')">
          发布话题
        </div>
        <!-- <div class="box1 card">
          <p style="margin: 0 0 10px 0">热门话题</p>
          <p>#软件开发#社团#竞赛</p>
        </div> -->
        <div style="display: flex">
          <div class="box2 card">
            <p style="margin: 0 0 10px 0">当前在线人数</p>
            <div style="display: flex; justify-content: center">
              <span
                v-text="onLineNum"
                v-if="pre"
                style="margin-right: 10px"
              ></span>
              <span class="like">
                <i class="el-icon-star-on" style="color: red"></i>
              </span>
            </div>
          </div>
          <div class="box3 card">
            <p style="margin: 0 0 0 0">邀请你的朋友</p>
            <hr />
            <p>
              本站网址:&nbsp;&nbsp;&nbsp;
              <span class="red-space"> www.baiyunsc.cn </span>
            </p>
          </div>
        </div>

        <div class="hot-topic">
          <h3>校园热搜榜</h3>
          <div class="time">更新于：{{ currentTime }}</div>
          <div class="content">
            <ul>
              <li v-for="(item, index) in postRanking" :key="index">
                <span>{{ index + 1 }}</span>
                <span
                  v-html="$options.filters.ellipsis(item.content)"
                  @click="$router.push(`/ywbd/postDetails?id=${item.id}`)"
                ></span>
                <span>{{ item.score }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getParentCommentType,
  getAllCommentType,
  getPostByScore,
  getCurrentTime,
} from "@/api/comment";
import { getPosts, getPostsByLike } from "@/api/comment/postManagement";
import { goodLike, goodCollect } from "../../api/service-good/goodService";
import ws from "@/api/websocket/index.js";
import SvgIcon from "../../components/SvgIcon.vue";
export default {
  components: { SvgIcon },
  data() {
    return {
      onLineNum: 1, //当前在线人数
      types: [],
      posts: [],
      postRanking: [], //帖子排名
      currentTime: "", //当前时间
      userInfo: {},
      likeForm: {
        id: "",
        type: 0,
      },
      collectForm: {
        id: "",
        type: 0,
      },
      avatar: "",
      pre: true,
      isPrivate: false,
      newTimePage: 1,
      likesPage: 1,
      limit: 5,
      total: 0,
      keyword: "",
      typeId: [],
      ptypeId: "",
      loading: false,
      options: [],
      search_class_type: 1,
      one_class: "",
      two_class: "",
      sort: 1, // 排序接口，1-最新，2-点赞
      noMorePosts: false, //控制是否还有更多帖子可以加载
      loadingForRoll: false, //控制加载中字段的显示
      hasErrorShown: false, // 添加这个属性来记录是否显示过错误
    };
  },
  async created() {
    try {
      await this.getOnLine();
      // await this.getParentCommentType() // 如果这个方法也是异步的，并且需要等待它的完成
      await this.searchForPosts();
      await this.getAllCommentType();
      await this.queryUserInfo();
      await this.queryPostByScore();
      await this.queryCurrentTime();

      // 确保types数组已经填充完毕
      this.types.forEach((value, index) => {
        if (this.$refs[`elDropdown-${index}`]) {
          const dropdownMenu = this.$refs[`elDropdown-${index}`].$children[0];
          dropdownMenu.$data.currentPlacement = "start";
        }
      });
    } catch (error) {
      console.error("Error in created hook:", error);
    }
  },
  filters: {
    //当渲染的文字超出9字后显示省略号
    ellipsis(value) {
      value = value.replace(/<.*?>/gi, ""); //把v-html的格式标签替换掉
      // if (value.length > 30) {
      //   return value.slice(0, 30) + "...";
      // }else{
      return value;
      // };
    },
  },
  mounted() {},
  computed: {
    disabled() {
      return this.loading || this.noMorePosts;
    },
  },
  methods: {
    getOnLine() {
      ws.getOnLine().then((res) => {
        if (res.success) {
          if (res.data.count === 0) {
            this.onLineNum = 1;
          } else {
            this.onLineNum = res.data.count;
          }
        }
      });
    },
    getTwoClass() {
      let arr = this.options.filter((item) => item.value === this.one_class);
      console.log(arr);
      return arr && arr[0] ? arr[0].children : [];
    },
    set_two_class(value) {
      this.two_class = value;
      this.typeId[0] = this.two_class;
      this.searchQuery();
    },
    set_one_class(value) {
      this.one_class = value;
      this.two_class = "";
      this.ptypeId = value;
      this.typeId = [];
      this.searchQuery();
    },
    set_search_class_type(value) {
      if (value && !this.$store.state.isJoin) {
        console.log(this.$store.state.isJoin);

        this.$message.warning("您还不是社团成员，快快加入吧");
        return;
      }
      this.isPrivate = value;
      this.searchQuery();
    },
    // 热搜热度
    queryPostByScore() {
      getPostByScore().then((res) => {
        if (res.code === 20000) {
          // 使用 map 方法遍历 res.data.list，并处理每个元素的 score 属性
          this.postRanking = res.data.list.map((item) => {
            // 使用 Math.floor 或 parseInt 截取 score 的整数部分
            return {
              ...item, // 保留原始对象的其他属性
              score: (Number(String(item.score).slice(0, 6)) * 100).toFixed(2), //String转换成字符串，截取前6位，再Number转换成数字，最后使用toFixed保留两位小数
            };
          });
        }
        console.log(this.postRanking);
      });
    },

    // 热搜时间
    queryCurrentTime() {
      getCurrentTime().then((res) => {
        if (res.code === 20000) {
          this.currentTime = res.data.date;
        }
      });
    },

    getAllCommentType() {
      getAllCommentType().then((res) => {
        this.types = res.data.List;
        this.types.forEach((item) => {
          let temp = {};
          temp.value = item.commentType.id;
          temp.label = item.commentType.name;
          let tempArr = [];
          item.commentTypeList.forEach((item) => {
            let temp = {};
            temp.value = item.id;
            temp.label = item.name;
            tempArr.push(temp);
          });
          temp.children = tempArr;
          this.options.push(temp);
          console.log("333", temp);
        });
      });
    },
    handleChange(value) {
      this.newTimePage = 1;
      this.posts = [];
      this.searchForPosts();
    },

    searchQuery() {
      this.newTimePage = 1;
      this.posts = [];
      this.searchForPosts();
    },
    //查询最新时间的帖子
    searchForPosts() {
      this.loading = true;
      this.loadingForRoll = true;
      const api = this.sort === 1 ? getPosts : getPostsByLike;
      if (!this.hasErrorShown) {
        api(
          this.newTimePage,
          this.limit,
          this.isPrivate,
          this.keyword,
          this.typeId[0] ? this.typeId[this.typeId.length - 1] : undefined,
          this.ptypeId
        )
          .then((res) => {
            this.loading = false;
            this.loadingForRoll = false;
            if (res.data.page.size === 0 && this.posts.length > 0) {
              // 如果没有更多帖子可以加载，设置 noMorePosts 为 true
              //this.$message.error("没有更多数据了");
              this.noMorePosts = true;
              return;
            }
            // this.$message.success("查询成功");
            // 将后端返回的数组 res.data.page.records 里面的数据全部推进 posts 数组中
            this.posts = [
              ...this.posts,
              ...res.data.page.records.map((record) => ({
                ...record,
                isGiveTheThumbs_up: record.isLiked,
                isCollects: record.isCollected,
              })),
            ];
          })
          .catch((err) => {
            this.loading = false;
            this.loadingForRoll = false;
            if (!this.hasErrorShown) {
              this.$message.error("查询失败");
              this.hasErrorShown = true; // 显示错误提示后，设置 hasErrorShown 为 true
            }
          });
      }
    },
    //加载更多根据时间排序的帖子
    loadNewTimePosts() {
      this.newTimePage += 1;
      this.searchForPosts();
    },

    //获取用户信息
    async queryUserInfo() {
      try {
        // 等待 action 完成
        await this.$store.dispatch("queryUser");

        // 此时 action 已完成，可以安全地访问 state
        this.userInfo = this.$store.state.userInfo;
        this.avatar = this.userInfo.avatar;

        console.log(this.$store.state.isJoin);
      } catch (error) {
        console.error("Error querying user info:", error);
      }
    },
    //点赞
    toggleLike(id, likes) {
      this.likeForm.id = id;

      goodLike(this.likeForm).then((res) => {
        if (res.code == 20000) {
          this.posts.forEach((item) => {
            if (item.id == id) {
              item.isGiveTheThumbs_up = !item.isGiveTheThumbs_up;
              if (item.isGiveTheThumbs_up) {
                this.$message.success("点赞成功");
                item.likes += 1;
              } else {
                //this.$message.success("取消点赞成功");
                item.likes -= 1;
              }
            }
          });
        } else {
          this.$message.error("点赞失败，请稍后再试！");
        }
      });
    },
    //收藏
    toggleCollect(id, collects) {
      this.collectForm.id = id;

      goodCollect(this.collectForm).then((res) => {
        if (res.code == 20000) {
          this.posts.forEach((item) => {
            if (item.id == id) {
              item.isCollects = !item.isCollects;
              if (item.isCollects) {
                this.$message.success("收藏成功");
                item.collects += 1;
              } else {
                //this.$message.success("取消收藏成功");
                item.collects -= 1;
              }
            }
          });
        } else {
          this.$message.error("收藏失败，请稍后再试！");
        }
      });
    },
    goToPostDetails(postId) {
      this.$router.push(`/post-details?id=${postId}`);
    },
  },
};
</script>

<style scoped>
.red-space {
  color: red;
}

body::-webkit-scrollbar {
  display: none;
  /* 隐藏Webkit浏览器的滚动条 */
}

.el-dropdown-link {
  cursor: pointer;
  color: #0080ff;
  font-size: 16px;
}

.lang-select-dropdown {
  position: absolute;
  top: 40px;
  left: 10px;
  margin: 0px;
  padding: 0px;
  min-width: max-content;
  text-align: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.search_input {
  margin-top: 20px;
  display: flex;
  /* justify-content: space-between; */
}

.search_class_type {
  justify-content: space-around;
}

.search_class_type div {
  display: inline-block;
  padding: 10px 40px 3px 40px;
  margin: 20px 0 5px 0;
  flex: 1;
  /* margin: 0 30px;
  flex: 1;
  text-align: center; */
  cursor: pointer;
}

.one_class {
  display: flex;
  font-size: 14px;
  font-weight: bold;
  /* margin-left: 20px; */
}

.one_class div {
  padding: 10px 10px 3px 10px;
  margin-bottom: 5px;
  cursor: pointer;
}

.two_class {
  display: flex;
  background: #f5f5f5;
  font-size: 12px;
  /* margin-left: 20px; */
}

.two_class div {
  padding: 10px 10px 5px 10px;
  margin-bottom: 5px;
  cursor: pointer;
}

.class_avtive {
  color: rgb(70, 100, 180);
  border-bottom: 2px solid rgb(70, 100, 180);
  background: linear-gradient(rgba(133, 254, 254, 0.493), rgb(255, 255, 255));
  border-radius: 15px 15px 0px 0px;
}

.class_avtive_1 {
  color: rgb(70, 100, 180);
  /* border-bottom: 2px solid rgb(70, 100, 180); */
}

.types_box {
  display: flex;
  justify-content: center;
  justify-items: center;
  /* margin-top: 10px; */
}

.types_box div {
  padding: 1% 3%;
  font-size: 12px;
}

.topic_box {
  box-shadow: 2px 2px 10px rgb(236, 236, 236);
  border: 1px solid rgb(236, 236, 236);
  border-radius: 2%;
  padding: 2% 5% 2% 5%;
  margin-top: 10px;
}

.top {
  overflow: hidden;
  border-bottom: 1px dotted grey;
  padding-bottom: 1%;
  display: flex;
  flex-direction: row;
}

.el-avatar > img {
  width: 100%;
}

.top p:first-of-type {
  font-size: 16px;
  float: left;
  margin-left: 8px;
}

.top p:last-of-type {
  float: right;
  font-size: 12px;
  color: gray;
}

.userContent {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  margin-top: -10px;
}

.header-name {
  font-size: 15px;
  float: left;
  margin-top: 13px;
  margin-left: 9px;
}

.header-fot {
  margin-left: 8px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.header-fot span {
  margin-left: 5px;
}

.middle {
  cursor: pointer;
  padding: 10px 0;
  word-wrap: break-word;
}

.middle p {
  margin-left: 8%;
}

.imgs {
  display: grid;
  grid-template-columns: 30% 30% 30%;
  grid-gap: 10px;
  justify-content: center;
  margin-bottom: 10px;
}

.imgs img {
  width: 100%;
  height: auto;
  background: gray;
  border-radius: 5%;
  margin: 10px;
}

.bottom {
  display: flex;
  border-top: 1px dotted grey;
  overflow: hidden;
  padding-top: 5px;
  align-items: center;
  justify-content: flex-end;
}

.handle_box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.dz:hover {
  cursor: pointer;
}

.sc:hover {
  cursor: pointer;
}

/* .dz:hover img:last-of-type{
            display: inline-block;
        }
        .dz:hover img:first-of-type{
            display: none;
        } */
/* .dz img:last-of-type{
            display: none;
        } */
.pl {
  margin-left: 10px;
  cursor: pointer;
}

.marginsLeft {
  margin-left: 5px;
}

.dz {
  font-size: 14px;
}

.sc {
  font-size: 14px;
  margin-left: 10px;
}

.watchs {
  font-size: 14px;
  margin-left: 10px;
}

.pl {
  font-size: 14px;
  margin-left: 10px;
}

.b {
  width: 50%;
  position: relative;
  justify-content: center;
  justify-items: center;
  padding-right: 15%;
}

.left_box {
  width: 100%;
}

.right_box {
  position: fixed;
  left: 70%;
  top: 100px;
  z-index: 100;
}

.card {
  background: #ffffff;
  height: auto;
  padding: 5% 0;
  margin-bottom: 20px;
  padding: 6% 8%;
}

.card p {
  margin: 0;
}

#fbht {
  background: linear-gradient(
    rgb(104, 104, 255),
    rgb(164, 108, 255),
    rgb(192, 116, 255)
  );
  text-align: center;
  color: white;
  font-weight: bold;
  border-radius: 10px;
  box-shadow: 2px 4px 5px lightgray;
  cursor: pointer;
}

.box1 {
  width: 350px;
  box-shadow: 2px 2px 6px lightgray;
  border-radius: 6px;
  border: 1px solid lightgrey;
}

.box1 p:last-of-type {
  font-size: 12px;
  color: gray;
  margin-top: 1%;
}

.box2 {
  border: 1px solid lightgrey;
  box-shadow: 2px 2px 6px lightgray;
  border-radius: 6px;
}

.box3 {
  border: 1px solid lightgrey;
  box-shadow: 2px 2px 6px lightgray;
  border-radius: 6px;
  margin-left: 8px;
}

.box3 p:last-of-type {
  font-size: 12px;
  color: gray;
}

.headPortrait {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  overflow: hidden;
  color: #fff;
  background: #c0c4cc;
}

.el-button.is-round {
  padding: 8px 16px;
}

.titles {
  margin-left: 33%;
  font-size: 13px;
  font-family: "LiSu";
}

.hot-topic {
  border: 1px solid lightgrey;
  box-shadow: 2px 2px 6px lightgray;
  border-radius: 6px;
  width: 400px;
}

.hot-topic h3 {
  font-size: 20px;
  color: #fff;
  text-align: center;
  background-color: #0080ff;
  margin: 10px 0;
}

.hot-topic .time {
  height: 14px;
  font-size: 16px;
  margin: 5px 20px;
}

.hot-topic .content ul {
  list-style: none;
  padding: 0px;
  margin: 10px 0;
}

.hot-topic .content ul li {
  height: 45px;
  font-size: 16px;
  border-bottom: 1px dotted #ddd;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.hot-topic span:nth-child(2) {
  width: 240px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.hot-topic span:nth-child(2) p {
  width: 240px;
  height: 45px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.hot-topic li:nth-child(1) span:nth-child(1) {
  color: red;
  font-weight: bold;
}

.hot-topic li:nth-child(2) span:nth-child(1) {
  color: #ff5c55;
  font-weight: bold;
}

.hot-topic li:nth-child(3) span:nth-child(1) {
  color: #ffa552;
  font-weight: bold;
}
</style>
